# ESP32 代码：uart_echo.py
from machine import UART
import time
from connect_wifi import connect_wifi as _connect_wifi
import network
from http_server import start_http_server
from uart_send import uart1_handler
import network
import socket

WIFI_CONNECTED = None

# 配置 Wi-Fi
this_wifi = network.WLAN(network.STA_IF)  # 设置工作站模式
this_wifi.active(True)

if __name__ == "__main__":
    uart = UART(1, baudrate=115200, tx=17, rx=16)
    ret = _connect_wifi(this_wifi)
    if ret[0] is 0:
        WIFI_CONNECTED = True
        print(f"Wifi Connected，IP地址：{ret[1]}")
    else:
        WIFI_CONNECTED = False
        print(ret[1])
    if WIFI_CONNECTED:
        addr = socket.getaddrinfo("0.0.0.0", 80)[0][-1]  # 监听 80 端口
        sock = socket.socket() # 避免被占用，先关闭再打开
        sock.close()
        sock = socket.socket()
        sock.bind(addr)
        sock.listen(5)
        print("HTTP 服务器已启动，访问地址: http://" + network.WLAN(network.STA_IF).ifconfig()[0])
    while True:
        if uart.any():  # 检查是否有数据
            received_data = uart.read().decode('utf-8').strip()
            ret = uart1_handler(received_data)
            uart.write(ret)
        if WIFI_CONNECTED:
            start_http_server(sock)
        
